# -*- coding: utf-8 -*-
import pytest
import json
import allure
from Common.mysql import redis_client
from pytest_assume.plugin import assume
from Common.mysql import app
from src.TestApiRun.api_run import ApiRun

@pytest.fixture
def get_case_data(request):
    case_data_str = request.config.getoption("--case_data")
    try:
        # 尝试将字符串解析为 JSON
        case_data = json.loads(case_data_str)
    except json.JSONDecodeError:
        # 如果解析失败，返回默认值
        case_data = {"project_name": "default_project", "feature": "default_feature", "case_data": []}
    return case_data


class TestRun:
    @pytest.fixture(autouse=True)
    def setup(self, get_case_data):
        self.case_data = get_case_data
        self.epic_name = self.case_data.get('projectName')
        self.feature_name = self.case_data.get('systemName')
        self.title_name = self.case_data.get('caseName')
        self.environment = self.case_data.get('environment')
        self.user_id = self.case_data.get('user_id')

    def test_run_api(self):
        with app.app_context():
            # 动态设置 Allure 报告的属性
            allure.dynamic.epic(self.epic_name)
            allure.dynamic.feature(self.feature_name)
            allure.dynamic.title(self.title_name)

            # 执行测试逻辑
            with allure.step("执行 API 请求"):
                res = ApiRun().api_request(self.environment, self.case_data, self.user_id)
                print(res)
                # TODO 接口配置需要增加接口断言配置，处理根据[key1][key2][key3]在response中去值的方法，并且如果key是数字这需要转成数字

        # for api in data:
        #     with allure.step(api['name']):
        #         if api['type'] == 'api':
        #             system_name = api['system_name']
        #             environment = api['environment']
        #             api_data = api['api_data']
        #
        #             response = ApiRun().api_request(environment, api_data)
        #             assert_data = api['assert']
        #             if assert_data:
        #                 for data in api_data:
        #                     if data['parameterType'] == '响应码断言':
        #                         with assume:
        #                             assert response.status_code == data['parameterName'][0], '接口返回响应码错误'
        #                     elif data['parameterType'] == '响应体断言':
        #                         with assume:
        #                             pass
        #                     elif data['parameterType'] == 'SQL断言':
        #                         with assume:
        #                             pass
        #         elif api['type'] == 'sql':
        #             # 执行 SQL 逻辑
        #             pass

#
# from flask import Flask, request, jsonify
# import subprocess
# import json
# import os
#
# app = Flask(__name__)
#
#
# @app.route('/run-tests', methods=['POST'])
# def run_tests():
#     # 获取前端传来的 JSON 数据
#     test_data = request.json
#     # 将测试数据保存到文件或直接传递给 pytest
#     with open('test_data.json', 'w') as f:
#         json.dump(test_data, f)
#
#     # 调用 pytest 命令执行测试
#     result = subprocess.run(['pytest', 'test_api.py', '--alluredir=allure-results'], capture_output=True, text=True)
#
#     # 返回执行结果
#     return jsonify({'status': 'success', 'output': result.stdout})




# 4. 配置 Allure 报告
# 确保你的 Pytest 配置可以生成 Allure 报告。在 pytest.ini 文件中添加以下内容：
# ini
# 复制
# [pytest]
# addopts = --alluredir=allure-results
# 5. 生成和查看 Allure 报告
# 在 Flask 应用执行完测试后，Allure 报告将被生成在 allure-results 目录中。你可以使用以下命令来生成一个可查看的报告：
# bash
# 复制
# allure serve allure-results

